<template>
  <div class="reason-wrap">
    <div style="margin-bottom: 15px;">
      <span>项目：</span>
      <el-select size="mini" style="width: 150px;" v-model="projectId" @change="onAppChange">
        <el-option v-for="item in permission_projectList" :value="item.app_id" :label="item.name" :key="item.app_id"></el-option>
      </el-select>
    </div>
      <div class="head">
        <div class="add">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addOne"
          >新增</el-button>
          <el-select
            v-model="labelId"
            placeholder="请选择"
            @visible-change="visibleChange"
            @change="save"
          >
            <el-option-group
              v-for="group in tagOpts"
              :label="group.mod_name"
              :key="group.mod_id"
            >
              <el-option
                v-for="item in group.options"
                :key="item.label_id"
                :label="item.label_name"
                :value="item.label_id"
              >
              </el-option>
            </el-option-group>
          </el-select>
        </div>

        <el-button
          type="primary"
          icon="el-icon-refresh"
          @click="getList"
        >刷新</el-button>
      </div>
      <div class="content">
        <el-table
          v-loading="loading"
          class="table-drag"
          :data="tableData"
          row-key="gl_id"
          height="660px"
        >
          <el-table-column
            align="center"
            width="100px"
          >
            <template v-slot:header>
              <el-tooltip content="按住后可以上下拖动排序！">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
            <template v-slot>
              <span class="drag-btn">
                <i class="el-icon-menu"></i>
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="反馈原因"
            align="center"
          >
            <template #default="{ row }">
              <p>{{ row.label_name }}</p>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
          >
            <template #default="{ row, $index }">
              <el-button
                type="text"
                @click="deleteOne(row, $index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

    <el-dialog
      width="500px"
      :visible.sync="addShow"
    >
      <div class="add-wrap"></div>
      <template #footer>
        <div class="btn tar">
          <el-button
            type="info"
            @click="addShow = false"
          >取消</el-button>
          <el-button
            type="primary"
            @click="save"
          >保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script type="text/javascript">
import { mapGetters } from 'vuex'
import {
  getTagGroupList,
  addTagGroup,
  modifyTagGroup,
  delTagGroup
} from '@/api/feedback/reason'
import { getModuleList } from '@/api/system/project'
import { getTagList } from '@/api/feedback/tagLib'
import Sortable from 'sortablejs'
export default {
  name: 'Reason',
  components: {},
  props: {},
  data () {
    return {
      projectId: null,
      loading: false,
      tableData: [],
      addShow: false,
      tagOpts: [],
      tagList: [],
      labelId: ''
    }
  },
  async created () {
    if (this.permission_projectList.length) {
      this.projectId = this.permission_projectList[0].app_id
    }
    this.init()
  },
  methods: {
    async init () {
      this.getList()
      await this.getModuleList()
      this.getTagList().then(list => {
        this.tagOpts = list
      })
    },
    onAppChange () {
      this.init()
    },
    getList () {
      this.loading = true
      getTagGroupList({
        page_index: 1,
        page_size: 666,
        pro_id: this.projectId
      })
        .then(res => {
          this.tableData = res.data.list.map(t => ({ ...t, label_idx: parseInt(t.label_idx) }))
          this.$nextTick(this.rowDropInit)
          this.loading = false
        })
        .catch(() => { })
    },
    // 模块列表
    getModuleList () {
      return getModuleList({
        page_index: 1,
        page_size: 666,
        pro_id: this.projectId,
        detail: true
      }).then(res => {
        this.moduleOpts = res.data.list
      })
    },
    getTagList (modId) {
      return new Promise((resolve, reject) => {
        const params = {
          page_index: 1,
          page_size: 666,
          pro_id: this.projectId
        }
        if (modId) params.mod_id = modId
        getTagList(params)
          .then(res => {
            this.tagList = res.data.list
            const map = res.data.list.reduce((map, it) => {
              if (!map[it.mod_id]) {
                map[it.mod_id] = [it]
              } else {
                map[it.mod_id].push(it)
              }
              return map
            }, {})
            const list = this.moduleOpts.reduce((arr, item) => {
              const options = map[item.mod_id]
              options && arr.push({
                mod_id: item.mod_id,
                mod_name: item.mod_name,
                mod_idx: item.mod_idx,
                options
              })
              return arr
            }, [])
            resolve(list)
          })
          .catch(err => reject(err))
      })
    },
    addOne () {
      this.addShow = true
    },
    deleteOne ({ gl_id }, index) {
      this.$confirm('确定要删除此条数据吗？', {
        title: '提示'
      })
        .then(() => {
          delTagGroup({ gl_id }).then(res => {
            if (res.code === 200) {
              this.tableData.splice(index, 1)
              this.$message.success('删除成功！')
            }
          })
        })
        .catch(() => { })
    },
    save () {
      if (!this.labelId) {
        this.$message.warning('请先勾选一项！')
        return
      }
      const len = this.tableData.length
      addTagGroup([
        {
          gro_id: 1,
          client_id: Date.now(),
          pro_id: this.projectId,
          label_id: this.labelId,
          label_idx: len ? this.tableData[len - 1].label_id : 0
        }
      ]).then(res => {
        if (res.code === 200) {
          this.getList()
          this.addShow = false
          this.$message.success('保存成功！')
        }
      })
    },
    visibleChange (show) {
      if (!show) this.labelId = ''
    },
    // 行拖拽
    rowDropInit () {
      if (this.dragObj) return
      this.dragObj = Sortable.create(
        document.querySelector('.table-drag tbody'),
        {
          handle: '.drag-btn',
          onEnd: ({ newIndex, oldIndex }) => {
            const currRow = this.tableData.splice(oldIndex, 1)[0]
            this.tableData.splice(newIndex, 0, currRow)
            modifyTagGroup({
              gl_id: currRow.gl_id,
              label_idx:
                newIndex === 0 ? 0 : this.tableData[newIndex - 1].gl_id
            })
          }
        }
      )
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList'])
  },
  beforeDestroy () {
    if (this.sortable1) {
      this.sortable1.destroy()
    }
  }
}
</script>

<style lang="scss" scoped>
.reason-wrap {
  .el-card {
    max-width: 800px;
    margin: 0 auto;
  }
  .head {
    margin-bottom: 10px;
  }
  .add {
    position: relative;
    display: inline-block;
    margin-right: 10px;
    .el-select {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      opacity: 0;
    }
  }
  .drag-btn {
    cursor: move;
  }
  .add-wrap {
    height: 360px;
  }
}
</style>
